include Gosu
include Globals
include ZOrder

class Results < Screen

  def initialize(game, screen, players, winner)
    super(game)
    @winner = winner
    unless @winner == :draw
      winner_info
    else
      @win_text = "The Round Was Drawn"
      @text_color = Color.new(255, 0, 255, 255)
      @end_match = false
    end
    @game = game
    @screen = screen
    @players = players
    @background = game.images["../3d_renders/front_background.png"]
    @back_color = Color.new(80, 255, 255, 255)
    @ship = game.images["../3d_renders/space_ship.png"]
    @star = game.load_tiles("win_star.png", 60, 60)
    @img_inc = 0.0
    @wait = 60

    @font = Font.new(game, Gosu.default_font_name, 50)
    @tx, @ty = WIDTH/2, 100
    @px, @py = 100, 100
    @star_angle, @factor = 0, 1
    @spin = :down

    # changed from 0.05 to 0.5 6/16/10
    @s_speed = 0.3
  end

  def winner_info
    @winner.wins += 1
    case @winner.id
    when :blue
      @win_text = 'Player Blue Wins'
      @text_color = Color.new(255, 0, 0, 255)
    when :red
      @win_text = 'Player Red Wins'
      @text_color = Color.new(255, 255, 0, 0)
    when :green
      @win_text = 'Player Green Wins'
      @text_color = Color.new(255, 0, 255, 0)
    when :purple
      @win_text = 'Player Purple Wins'
      @text_color = Color.new(255, 255, 0, 255)
    end
    if @winner.wins == 5
      @win_text += ' the Match!'
      @end_match = true
    else
      @win_text += '!'
      @end_match = false
    end
  end

  def update
    star_spin(@s_speed)
    @wait -= 1
  end

  def draw
    @background.draw(0, 0, BACKGROUND, 1, 1, @back_color)
    @players.each_with_index do |player, y|
      @ship.draw_rot(@px, @py*(y+2), DASHBOARD, 0, 0.5, 0.5, 1, 1, player.color)
      player.wins.times do |x|
        # added 6/16/10 for enhanced graphics
        @star[@img_inc.to_i].draw_rot(@px*(x+2), @py*(y+1) + 100, DASHBOARD,
                                      @star_angle, 0.5, 0.5)
      end
      @font.draw_rel("Died #{player.deaths} times", @px*8, 
                     @py*(y+1) + 100, TEXT, 0.5, 0.5)
    end
    @font.draw_rel(@win_text, @tx, @ty, TEXT, 0.5, 0.5, 1, 1, @text_color)
  end

  def button_down(id)
    #if id == KbReturn or id == KbEscape or id == KbSpace
    if @wait <= 0
      @active = false
      if @end_match
        @screen.deactivate
      else
        @screen.start_level
      end
    end
  end

  def star_spin(speed)
    # deprecated 6/16/10 for enhanced graphics
    # this old method sucked anyway. Could've used a Sine function like in DD
    #if @spin == :down
    #  @factor -= speed
    #  @spin = :up if @factor <= -1
    #else
    #  @factor += speed
    #  @spin = :down if @factor >= 1
    #end
    
    # 20 frames in the sprite and we want 1 cycle in 40 frames
    @img_inc += speed
    @img_inc %= 20
    # therefore speed must be 0.5
  end

  def activate
    @active = true
  end

  def ended?
    !@active
  end

end
